package com.bluefox.search.lucene;

import com.chenlb.mmseg4j.analysis.MMSegAnalyzer;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Paths;
/**
 * @Author : 孙峰
 * @Description: 配置项
 * @Date : 2021/9/20  22:52
 */
@Slf4j
@Component
public class LuceneConfig {
    @Autowired
    private Environment env;
    /**
     * 索引目录
     */
    private static Directory directory;
    /**
     * 分词器
     */
    private static Analyzer analyzer;
    /**
     * 写索引的配置
     */
    private static IndexWriterConfig indexWriterConfig;
    /**
     * 索引目录
     */
    private static String indexPath = "D:/lucene/";

    private ResourceLoader loader = new DefaultResourceLoader();
    static {
        try {
            //文件目录

            directory = FSDirectory.open(Paths.get(indexPath));



            //分词器可以换
            // analyzer = new StandardAnalyzer();
            analyzer = new MMSegAnalyzer();

            // 指定在JVM退出前要执行的代码
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    LuceneUtil.indexChanged();
                    try {
                        if (null != directory) {
                            directory.close();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

        } catch (Exception e) {
            log.error("lucence 配置错误.....");
            throw new RuntimeException(e);
        }
    }
    public static Directory getDirectory() {
        return directory;
    }
    public static Analyzer getAnalyzer() {
        return analyzer;
    }

    public static IndexWriterConfig getIndexWriterConfig() {
        indexWriterConfig = new IndexWriterConfig(analyzer);
        // 如果不存在则创建，否则追加
        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
        return indexWriterConfig;
    }
}
